/*
 * @Author: i@rysa.cn
 * @Date: 2022-06-10 17:21:12
 * @LastEditTime: 2022-06-12 11:43:46
 * @LastEditors: i@rysa.cn
 * @Description:
 * @FilePath: \go-utils\logger\zap.go
 */
package logger

import (
	"strings"
	"time"

	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

var zaplogger *zap.Logger

func NewZapLogger() *zap.Logger {
	return zaplogger
}

func InitZapLogger(filename string) error {
	cfg := zapcore.EncoderConfig{
		MessageKey:     "msg",
		TimeKey:        "time",
		EncodeTime:     zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05"),
		LevelKey:       "level",
		NameKey:        "name",
		CallerKey:      "caller",
		FunctionKey:    zapcore.OmitKey,
		StacktraceKey:  "stacktrace",
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.LowercaseLevelEncoder,
		EncodeDuration: zapcore.SecondsDurationEncoder,
		EncodeCaller:   zapcore.ShortCallerEncoder,
	}
	zap.NewProductionConfig()
	enc := zapcore.NewJSONEncoder(cfg)
	// f, err := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_RDWR, os.ModePerm)
	file := strings.Replace(filename, "log.log", time.Now().Format("2006-01-02")+".log", 1)
	f, err := rotatelogs.New(file, rotatelogs.WithLinkName(filename), rotatelogs.WithMaxAge(time.Hour*24*30), rotatelogs.WithRotationTime(time.Hour*24))
	if err != nil {
		return err
	}
	zaplogger = zap.New(zapcore.NewCore(enc, zapcore.AddSync(f), zapcore.DebugLevel), zap.AddCaller())
	return nil
}
